package com.sr.examination.user;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.RemoteException;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.sr.examination.R;
import com.sr.examination.user.base.FileUploadModel;
import com.tl.commonlibrary.tool.UIUtils;
import com.tl.commonlibrary.ui.BaseFragmentActivity;
import com.yancy.imageselector.ImageConfig;
import com.yancy.imageselector.ImageSelector;

import org.json.JSONException;

/**
 * 设置用户信息的P类
 */
public class UpImageModel {

    private final static int WRITE_EXTERNAL_STORAGE_REQUEST_CODE = 1;

    private BaseFragmentActivity mContext;
    private ImageConfig mImageConfig;
    private IUserInfoModifyListener mModifyListener;
    private FileUploadModel mImageUploadPresenter;
    private IAvatarUploadedListener mIAvatarUploadedListener;

    private TextView mProgressBar;

    public void setmProgressBar(TextView mProgressBar) {
        this.mProgressBar = mProgressBar;
    }

    public UpImageModel(BaseFragmentActivity context) {
        this.mContext = context;
        initImageConfig(true);
    }

    public UpImageModel(BaseFragmentActivity context, boolean isCrop) {
        this.mContext = context;
        initImageConfig(isCrop);
    }

    public void setUserInfoModifyListener(IUserInfoModifyListener listener) {
        mModifyListener = listener;
    }

    public void setAvatarUploadedListener(IAvatarUploadedListener listener) {
        mIAvatarUploadedListener = listener;
    }

    public void changePortrait(Fragment fragment) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {
                //申请WRITE_EXTERNAL_STORAGE权限
                ActivityCompat.requestPermissions(mContext, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        WRITE_EXTERNAL_STORAGE_REQUEST_CODE);
            } else {
                if(fragment!=null){
                    ImageSelector.open(fragment, mImageConfig);
                }else{
                    ImageSelector.open(mContext, mImageConfig);
                }
            }
        } else {
            if(fragment!=null){
                ImageSelector.open(fragment, mImageConfig);
            }else{
                ImageSelector.open(mContext, mImageConfig);
            }
        }
    }


    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == WRITE_EXTERNAL_STORAGE_REQUEST_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                ImageSelector.open(mContext, mImageConfig);
            } else {
                // Permission Denied
            }
        }
    }

    private void initImageConfig(boolean isCrop) {
        ImageConfig.Builder builder = new ImageConfig.Builder(new GlideLoader())
                // 如果在 4.4 以上，则修改状态栏颜色 （默认黑色）
//                .steepToolBarColor(mContext.getResources().getColor(R.color.white))
                // 标题的背景颜色 （默认黑色）
                .titleBgColor(mContext.getResources().getColor(R.color.white))
                // 提交按钮字体的颜色  （默认白色）
                .titleSubmitTextColor(mContext.getResources().getColor(R.color.text_black_main))
                // 标题颜色 （默认白色）
                .titleTextColor(mContext.getResources().getColor(R.color.text_black_main))
                .singleSelect()
                .showCamera()
                .scale()
                .filePath("/" + mContext.getPackageName() + "/image/");

        if(isCrop){
            builder.crop(1,1,400,400);
        }

        mImageConfig = builder.build();

    }

    public void startUpload(String avatarPath) {
        mImageUploadPresenter = new FileUploadModel(mContext, mIFileUploadedListener);
        mImageUploadPresenter.startUpload(avatarPath, FileUploadModel.FILE_TYPE_HEAD);
    }

//    @Override
//    public void onSucceed(String url, ResultModel resultModel) throws JSONException, RemoteException {
//    }
//
//    @Override
//    public void onFailure(String url, ResultModel resultModel) {
//        super.onFailure(url, resultModel);
//        Toast.makeText(mContext, resultModel.getMsg(), Toast.LENGTH_LONG).show();
//    }

    private FileUploadModel.IFileUploadedListener mIFileUploadedListener = new FileUploadModel.IFileUploadedListener() {

        @Override
        public void onFileUploadProgress(long currentSize, long totalSize) {
            if(mProgressBar!=null){
                mContext.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mProgressBar.setVisibility(View.VISIBLE);
                        mProgressBar.setText(R.string.up_loading);
                    }
                });
            }

        }

        @Override
        public void onFileUploadedSuccess(String url) {
            if (mIAvatarUploadedListener != null) {
                mIAvatarUploadedListener.onAvatarUploadedSucceed(url);
            }
            if(mProgressBar!=null){
                mContext.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mProgressBar.setVisibility(View.GONE);
                    }
                });
            }
        }

        @Override
        public void onFileUploadedFailure() {
            mContext.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    UIUtils.showToast("图片上传失败,请重新上传", Toast.LENGTH_LONG);
                    if(mProgressBar!=null) {
                        mProgressBar.setVisibility(View.VISIBLE);
                        mProgressBar.setText(R.string.up_load_err);
                    }
                }
            });
        }
    };

    public interface IUserInfoModifyListener {
        public void onModifySucceed();
    }

    public interface IAvatarUploadedListener {
        public void onAvatarUploadedSucceed(String url);
    }
}
